/*
 * Copyright (C) 2010 beworx.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package fr.gdi.android.news;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.text.TextUtils;
import android.widget.RemoteViews;
import fr.gdi.android.news.utils.Constants;
import fr.gdi.android.news.utils.Constants.Preferences;
import fr.gdi.android.news.utils.PreferenceUtils;
import fr.gdi.android.news.utils.Utils;


public class NotificationUpdater extends BroadcastReceiver {

    private static final int SHORTCUT_NOTIFICATION = 1;
    private static final int ON_REFRESH_NOTIFICATION = 2;
    
	// cache
	private Notification notification;
	
	@Override
	public void onReceive(final Context context, Intent intent) {

		String action = intent.getAction();
		if ( Intent.ACTION_BOOT_COMPLETED.equals(action) || 
             Constants.Actions.START_NOTIFICATION.equals(action) ) {
		    int widgetCount = Utils.getAllWidgetIds(context).length;
			boolean show = PreferenceUtils.getBooleanPreference(context, Constants.Preferences.SHOW_ONGOING_NOTIFICATION);
			if ( show && widgetCount > 0 ) 
		    {
			    sendNotification(context);
		    }
			else 
			{
			    NotificationManager mgr = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
		        mgr.cancel(SHORTCUT_NOTIFICATION);
			}
		} 
		else if ( Constants.Actions.REFRESH_NOTIFICATION.equals(action) && 
		          PreferenceUtils.getBooleanPreference(context, Preferences.NOTIFY_ON_UPDATE) ) {
		    int appWidgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, -1);
		    String title = PreferenceUtils.getWidgetTitle(context, appWidgetId);

		    CharSequence tickerText = context.getString(R.string.notification_updates);         
		    long when = System.currentTimeMillis();         
		    CharSequence contentTitle = context.getString(R.string.notification_title); 
		    CharSequence contentText = String.format(context.getString(R.string.notification_reloaded), title);
		    
		    Intent notificationIntent = new Intent(Constants.Actions.NONE);
		    PendingIntent contentIntent = PendingIntent.getBroadcast(context, -1, notificationIntent, 0);

		    Notification transientNotification = new Notification(R.drawable.icon, tickerText, when);
		    transientNotification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
		    
		    transientNotification.icon = R.drawable.icon;
		    if ( PreferenceUtils.getBooleanPreference(context, Preferences.NOTIFICATION_VIBRATE) ) 
		    {
		        transientNotification.defaults |= Notification.DEFAULT_VIBRATE;
		    }
		    if ( PreferenceUtils.getBooleanPreference(context, Preferences.NOTIFICATION_FLASH) )
		    {
    		    transientNotification.defaults |= Notification.DEFAULT_LIGHTS;
    		    transientNotification.ledARGB = 0xff00ff00;
    		    transientNotification.ledOnMS = 300;
    		    transientNotification.ledOffMS = 1000;
		    }
		    transientNotification.flags |= Notification.FLAG_AUTO_CANCEL;

	        NotificationManager mgr = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
	        mgr.notify(ON_REFRESH_NOTIFICATION, transientNotification);
		}
	}
	
	private synchronized void sendNotification(Context context) {
		
		if (notification == null) {
			
			// create and cache notification
			notification = new Notification();
			notification.flags |= Notification.FLAG_ONGOING_EVENT;
			notification.flags |= Notification.FLAG_NO_CLEAR;
			RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.status_bar_event);
			int color = TextUtils.equals(Preferences.NOTIFICATION_COLOR_BLACK, PreferenceUtils.getStringPreference(context, Preferences.NOTIFICATION_COLOR, null)) ? Color.BLACK : Color.WHITE;
            views.setTextColor(R.id.notif_summary, color);
            views.setTextColor(R.id.notif_title, color);
            notification.contentView = views;
		}
		
		Intent intent = new Intent(context, DialogSettingsActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		notification.contentIntent = PendingIntent.getActivity(context, 0, intent, 0);
		
		NotificationManager mgr = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
		notification.icon = R.drawable.ic_placeholder;
				
		long hiddenTime = Constants.SDK_VERSION >= 9 ? -Long.MAX_VALUE : Long.MAX_VALUE;
		notification.when = hiddenTime; // align left (0) / right (max) in status bar
		mgr.notify(SHORTCUT_NOTIFICATION, notification);
	}
}
